﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.Practices.Unity;
using Web.SystemConfig.Business;
using Web.SystemConfig.Services;
using EPlanet.Web.UI.WebControls;
using DreamBuilder.UI.UserControls;
using CommonModule;
using DreamBuilder.Core.Message;
using DreamBuilder.Core.Container;
using DreamBuilder.Core.Log;
using Web.SystemLogin.Business;
using System.Threading;
using System.Configuration;

namespace Web.Views.SystemConfig
{
    public partial class Auth_User : PageBase
    {
        #region 变量定义
        /// <summary>
        /// Business类
        /// </summary>
        [Dependency]
        public IAuth_User Auth_UserComponent
        {
            get;
            set;
        }

        string topOrgId = ConfigurationManager.AppSettings["OrgTopID"];
        #endregion

        #region PageLoad
        protected void Page_Load(object sender, System.EventArgs e)
        {
           try{
               SetPageProperty();
            InitControlsCultureInfo();
            if (!IsPostBack)
            {
                ShowList();
            }
            CreateToolMenu(Toolbar1, ToolMenuType.TYPE_MainList);
            base.CheckListAuthorities(Toolbar1, uclist);
           }
           catch (Exception ex)
           {
               WriteErrorLog(ex.Message);
               ExceptionMsg();
           }
        }
        /// <summary>
        /// 设置页面的菜单属性
        /// </summary>
        private void SetPageProperty()
        {
            this.DBHelpName = DBHelperString.Dictionary;
            base.MenuID = "ePlanet.Configuration.Auth_User";
        }
        /// <summary>
        /// 显示列表,为列表控件的单据id赋值
        /// </summary>
        private void ShowList()
        {
            uclist.VoucherID = "vch_Auth_User";
            string filter = "P_Auth_User.ORG_ID != '" + topOrgId + "'";
            if (Request.QueryString["Parent_ID"] != null && Request.QueryString["Parent_ID"] != "" && Request.QueryString["Parent_ID"] != "" + topOrgId + "")
            {
                filter = "P_Auth_User.ORG_ID = '" + Request.QueryString.Get("Parent_ID").ToString() + "'";
            }
            this.uclist.FilterSqlWhere = filter;
        }
        /// <summary>
        /// 初始化控件多语信息
        /// </summary>
        private void InitControlsCultureInfo()
        {
        }
        #endregion

        #region 上移下移刘英男添加
        private Boolean ShowMoveUpInfo(string pkValue)
        {
            ResultInfo result = new ResultInfo();
            if (!string.IsNullOrEmpty(pkValue))
            {
                DataTable dt = Auth_UserComponent.GetUserInfo(pkValue);
                int order = Convert.ToInt32(dt.Rows[0]["Order_Num"].ToString());
                string orgID = dt.Rows[0]["ORG_ID"].ToString();
                int minOrder = Auth_UserComponent.GetMinOrgNum(orgID);
                if(order>minOrder)
                {                  
                   result = Auth_UserComponent.MoveUpOrder(pkValue);
                    #region 记录操作日志
                    ILogger log = UContainer.Resolve<ILogger>(Category.SMInfoLog);
                    OnlineUser ou = new OnlineUser();
                    string smallCategory =((int)OracleLogType.System).ToString();
                    string operationMessage = "点击了用户菜单下的上移按钮，上移了主键为" + pkValue+"的记录" ;
                    string strLog = smallCategory + this.CurrentUser.User_Name + operationMessage;
                    log.Info(strLog);
                    #endregion
                    this.ShowMsg("上移成功");
                }
                else
                {
                    this.ShowMsg("不能上移");
                }
            }
            else
            {
            //result.bSuccess = false;
            //result.ErrorDesc = "ERRDAE07";
            //DisplayMessage(result.ErrorDesc);
            }
            return true;
        }
        private Boolean ShowMoveDownInfo(string pkValue)
        {
            ResultInfo result = new ResultInfo();
            
            if (!string.IsNullOrEmpty(pkValue))
            {
                DataTable dt = Auth_UserComponent.GetUserInfo(pkValue);
              int order = Convert.ToInt32(dt.Rows[0]["Order_Num"].ToString());
              string orgID = Request.QueryString.Get("Parent_ID").ToString();
              int MaxNum = Auth_UserComponent.MaxOrgNum(orgID);
                if (order>=MaxNum)
                {
                    this.ShowMsg("不能下移");
                }
                else
                {
                result = Auth_UserComponent.MoveDownOrder(pkValue);
                #region 记录操作日志
                ILogger log = UContainer.Resolve<ILogger>(Category.SMInfoLog);
                OnlineUser ou = new OnlineUser();
                string smallCategory = ((int)OracleLogType.System).ToString();
                string operationMessage = "点击了用户菜单下的下移按钮，下移了主键为" + pkValue + "的记录";
                string strLog = smallCategory + this.CurrentUser.User_Name + operationMessage;
                log.Info(strLog);
                #endregion
                this.ShowMsg("下移成功");
                }
            }
            else
            {
                result.bSuccess = false;
                result.ErrorDesc = "ERRDAE07";
                DisplayMessage(result.ErrorDesc);
            }
            return true;
        }
        #endregion

        #region 新增

        /// <summary>
        /// 新增数据
        /// </summary>
        private void AddNewData()
        {      
            RedirectEdit(string.Empty);
        }        
        #endregion

        #region 删除
         /// <summary>
        /// 删除单条记录
        /// </summary>
        /// <param name="pkValue"></param>
        /// <returns></returns>
        private Boolean DeleteData(string pkValue)
        {
            ResultInfo result = new ResultInfo();
            if (!string.IsNullOrEmpty(pkValue))
            {
                DataTable dtUser=Auth_UserComponent.GetUserInfo(pkValue);
                string pkName = dtUser.Rows[0]["User_Name"].ToString();
                result = Auth_UserComponent.DeleteUser(pkValue);
                string operationMessage = this.CurrentUser.Real_Name + "删除了" + pkName + "[" + pkValue + "]用户";
                WriteUserLog(operationMessage,OracleLogType.System);               
            }
            else
            {
                result.bSuccess = false;
                result.ErrorDesc = "ERRDAE07";
                DisplayMessage(result.ErrorDesc);
            }
            return true;
        }
        /// <summary>
        /// 删除列表选中的多条记录
        /// </summary>
        private void DeleteSelectData()
        {
            string pkValues = uclist.GetListCheckedPrimaryValues();
            foreach (string pkValue in System.Text.RegularExpressions.Regex.Split(pkValues, ","))
            {
                DeleteData(pkValue); 
            }
        }
        #endregion

        #region 事件处理方法
        /// <summary>
        /// 工具条事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Toolbar1_MenuItemClick(object sender, MenuItemClickEventArgs e)
        {try{
            switch (e.EventItem.ID.ToString().ToLower())
            {
                case "tbadd":
                    if (Request.QueryString["Parent_ID"] != "" + topOrgId + "")
                        AddNewData();
                    else{
                        ScriptManager.RegisterClientScriptBlock(Page, GetType(), "no_parent_id", "alert('请先选择组织机构.')", true);
                    }

                    break;
                case "tbdelete":
                    DeleteSelectData();
                    this.uclist.RefreshList();
                    break;
                case "tbexport":
                    this.ExportListToExcel(uclist.GetExportData(), this);
                    break;
                case "tbhelp":
                    break;
            }
        }
        catch (Exception ex)
        {
            WriteErrorLog(ex.Message);
            ExceptionMsg();
        }
        }
        /// <summary>
        /// 列表事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uclistEmployee_VoucherListRowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow gridViewRow = ((Control)e.CommandSource).NamingContainer as GridViewRow;
             
            if (gridViewRow == null) return;
            int rowIndex = gridViewRow.RowIndex;
            GridView epGridView = sender as GridView;
            
            if (epGridView == null) return;
            string pkValue = epGridView.DataKeys[rowIndex][0].ToString().Trim();

            DataTable dt = Auth_UserComponent.GetUserInfo(pkValue);
            string pkName = dt.Rows[0]["User_Name"].ToString();
            string userIdUp = null;
            string userNameUp = null;
            string userIdDown = null;
            string userNameDown = null;
            int order = Convert.ToInt32(dt.Rows[0]["Order_Num"].ToString());
            string parentid = dt.Rows[0]["ORG_ID"].ToString();
            int maxOrder = Auth_UserComponent.MaxOrgNum(parentid);
            int minOrder = Auth_UserComponent.GetMinOrgNum(parentid);
            //每而显示数
            int maxRowIndex = this.uclist.ShowRecordsCount - 1;
            int total = (this.uclist.pager.RecordCount / this.uclist.ShowRecordsCount) + 1;
            switch (e.CommandName.Trim().ToLower())
            {
                case "edit":
                    RedirectEdit(pkValue);
                    break;
                case "delete":
                    {
                        if (DeleteData(pkValue) == true)
                        {
                            this.uclist.RefreshList();
                        }
                    }
                    break;
                case "view":
                    {
                        ShowViewInfo(uclist.VoucherID, pkValue);
                    }
                    break;
                    //add by 刘英男 上移下移
                case "moveup":
                    {

                        if (rowIndex == 0)
                        {
                            DataTable dtOrder = this.uclist.GetListData(-1, "P_Auth_User.Order_Num");
                            if (dtOrder == null || order <= minOrder)
                            {
                                this.ShowMsg("不能上移");
                            }
                            else
                            {

                                 userIdUp = dtOrder.Rows[maxRowIndex][0].ToString();
                                string orgId = Auth_UserComponent.GetUserInfo(userIdUp).Rows[0]["ORG_ID"].ToString();
                               userNameUp = Auth_UserComponent.GetUserInfo(userIdUp).Rows[0]["User_Name"].ToString();
                                if (parentid != orgId)
                                {
                                    this.ShowMsg("上下两条数据不属于同一组织机构，不能上移");
                                }
                                else
                                {
                                    Auth_UserComponent.MoveUserOrder(userIdUp, pkValue);
                                    string operationMessage = this.CurrentUser.Real_Name + "上移了" + pkName + "[" + pkValue + "]用户" + "把它和上一用户" + userNameUp + "[" + userIdUp + "]交换了位置";
                                    WriteUserLog(operationMessage,OracleLogType.System);    
                                    this.uclist.pager.CurrentPageIndex--;
                                    this.uclist.SetAspNetPagerInfo(this.uclist.pager);
                                    this.uclist.RefreshList();
                                    epGridView.Rows[epGridView.Rows.Count - 1].BackColor = System.Drawing.Color.FromArgb(166, 225, 250);
                                }
                            }
                        }
                        else
                        {
                            string useridup = epGridView.DataKeys[rowIndex - 1][0].ToString().Trim();
                            string orgId = Auth_UserComponent.GetUserInfo(useridup).Rows[0]["ORG_ID"].ToString();
                            userNameUp = Auth_UserComponent.GetUserInfo(useridup).Rows[0]["User_Name"].ToString();
                            if (parentid != orgId)
                            {
                                this.ShowMsg("上下两条数据不属于同一组织机构，不能上移");
                            }
                            else
                            {
                                Auth_UserComponent.MoveUserOrder(useridup, pkValue);
                                string operationMessage = this.CurrentUser.Real_Name + "上移了" + pkName + "[" + pkValue + "]用户" + "把它和上一用户" + userNameUp + "[" + useridup + "]交换了位置";
                                WriteUserLog(operationMessage,OracleLogType.System);  
                                this.uclist.RefreshList();
                                epGridView.Rows[rowIndex - 1].BackColor = System.Drawing.Color.FromArgb(166, 225, 250);
                            }
                        }
                    }
                    this.uclist.RefreshList();
                    break;                    
                case "movedown":
                    {
                        //if (this.uclist.pager.CurrentPageIndex == total && order == maxOrder)
                        if (order >= maxOrder)
                        {
                                this.ShowMsg("不能下移");
                        }
                        else
                        {
                            if (rowIndex == maxRowIndex)
                            {
                                DataTable dtOrder = this.uclist.GetListData(1, "P_Auth_User.Order_Num");
                               userIdDown = dtOrder.Rows[0][0].ToString();
                                string orgId = Auth_UserComponent.GetUserInfo(userIdDown).Rows[0]["ORG_ID"].ToString();
                                userNameDown = Auth_UserComponent.GetUserInfo(userIdDown).Rows[0]["User_Name"].ToString();
                                if (parentid != orgId)
                                {
                                    this.ShowMsg("上下两条数据不属于同一组织机构,不能下移");
                                }
                                else
                                {
                                    Auth_UserComponent.MoveUserOrder(userIdDown, pkValue);
                                    string operationMessage = this.CurrentUser.Real_Name + "下移了" + pkName + "[" + pkValue + "]用户" + "把它和下一用户" + userNameDown + "[" + userIdDown + "]交换了位置";
                                    WriteUserLog(operationMessage,OracleLogType.System);  
                                    this.uclist.pager.CurrentPageIndex++;
                                    this.uclist.SetAspNetPagerInfo(this.uclist.pager);
                                    this.uclist.RefreshList();
                                    epGridView.Rows[0].BackColor = System.Drawing.Color.FromArgb(166, 225, 250);
                                }
                            }
                            else
                            {
                                userIdDown = epGridView.DataKeys[rowIndex + 1][0].ToString().Trim();
                                string orgId = Auth_UserComponent.GetUserInfo(userIdDown).Rows[0]["ORG_ID"].ToString();
                                userNameDown = Auth_UserComponent.GetUserInfo(userIdDown).Rows[0]["User_Name"].ToString();
                                if (parentid != orgId)
                                {
                                    this.ShowMsg("上下两条数据不属于同一组织机构,不能下移");
                                }
                                else
                                {
                                    Auth_UserComponent.MoveUserOrder(userIdDown, pkValue);
                                    string operationMessage = this.CurrentUser.Real_Name + "下移了" + pkName + "[" + pkValue + "]用户" + "把它和下一用户" + userNameDown + "[" + userIdDown + "]交换了位置";
                                    WriteUserLog(operationMessage,OracleLogType.System); 
                                    this.uclist.RefreshList();
                                    epGridView.Rows[rowIndex + 1].BackColor = System.Drawing.Color.FromArgb(166, 225, 250);
                                }

                            }
                        }
                    }
                    this.uclist.RefreshList();
                    break;                
            }
        }
        #endregion

        #region 页面跳转
        /// <summary>
        /// 跳转到编辑页面
        /// </summary>
        /// <param name="pkValue">主键值</param>
        private void RedirectEdit(string pkValue)
        {
            string parentID = Request.QueryString.Get("Parent_ID").ToString();
            Response.Redirect("Auth_UserEdit.aspx?pkValue=" + pkValue + "&Parent_ID=" + parentID);
        }
        #endregion

        #region OnInit
        override protected void OnInit(EventArgs e)
        {
            //
            //CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>
        /// 添加页面及控件事件
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            this.Toolbar1.MenuItemClick += new EPlanet.Web.UI.WebControls.MenuItemClickedEventHandler(Toolbar1_MenuItemClick);
            this.uclist.VoucherListRowCommand += new global::DreamBuilder.UI.UserControls.VoucherListRowCommandEventHandler(uclistEmployee_VoucherListRowCommand);
            this.uclist.ShowMoveUpCommand = false;
            this.uclist.ShowMoveDownCommand = false;
        }
        #endregion
    }
}
